import 'dart:async';

import 'package:example/base/component_container.dart';
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action, Page;

import '../../base/component_effect.dart';

Widget buildView(
  Map<String, dynamic> state,
  Dispatch dispatch,
  ViewService viewService,
) {
  return DYComponentContainer(
      data: state,
      child: _ComponentWidget(
          state: state, dispatch: dispatch, viewService: viewService));
}

class _ComponentWidget extends StatefulWidget {
  final Map<String, dynamic> state;
  final Dispatch dispatch;
  final ViewService viewService;

  const _ComponentWidget(
      {required this.state, required this.dispatch, required this.viewService});

  @override
  State<StatefulWidget> createState() {
    return _ComponentWidgetState();
  }
}

class _ComponentWidgetState extends State<_ComponentWidget> {
  late StreamController<String> _streamController;

  @override
  void initState() {
    super.initState();
    _streamController = StreamController<String>();
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<String>(
        stream: _streamController.stream,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          final content =
              ComponentValue.stringInfoValueForUIKey(widget.state, 'content');
          return GestureDetector(
            onTap: () {
              widget.state['info']['content'] =
                  widget.state['info']['content'] == 'red' ? 'blue' : 'red';
              widget.dispatch(CommonComponentActionCreator.customAction(
                  widget.state, 'actions'));
              _streamController.add(widget.state['info']['content']);
            },
            child: Container(
              color: widget.state['info']['content'] == 'red'
                  ? Colors.red
                  : Colors.blue,
              child: Center(
                child: Text(
                  widget.state['info']['content'] == 'red'
                      ? '$content, 点我变蓝色'
                      : '$content, 点我变红色',
                  style: const TextStyle(color: Colors.white, fontSize: 20),
                ),
              ),
            ),
          );
        });
  }
}
